package com.geekhalo.demo.mq.event.bug;

import com.geekhalo.demo.mq.event.BaseController;
import com.geekhalo.demo.mq.event.Order;
import com.geekhalo.lego.core.web.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("mq/event/bug")
@Slf4j
public class SMSTimeoutController extends BaseController {

    @PostMapping("paySuccess")
    @Transactional
    public RestResult<Boolean> paySuccess(@RequestParam Long orderId, @RequestParam String token){
        // 验证 token，保障有效性
        checkToke(token);

        // 加载订单信息
        Order order = findById(orderId);
        if (order == null){
            return RestResult.success(false);
        }
        // 支付成功，更新订单状态
        order.paySuccess();
        // 将变更更新到数据库
        updateOrder(order);

        // 由于对这块逻辑不太放心，所以增加了 try-catch 逻辑
        // 避免对主流程的影响
        try {
            // 发送短信通知
            sendSMSNotice(order);
        }catch (Exception e){
            log.error("Failed to Send SMS Notice for Order {}", order.getId(), e);
        }

        return RestResult.success(true);
    }

}
